/**
 * Copyright (C), 2020, 安徽贝慕信息科技有限公司
 * FileName: UserDetailsControllerImpl
 * Author:   Allen
 * Date:     2020/8/27
 * Description: 统一用户登陆实现类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bim.marvel.rest.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bim.marvel.auth.common.entity.UserInfo;
import com.bim.marvel.auth.common.resource.UserDetailsResource;
import com.bim.marvel.openapi.core.entity.DealerUserDO;
import com.bim.marvel.openapi.core.service.impl.DealerUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;

/**
 * 统一用户登陆实现类
 *
 * @author Allen
 * @date 2020/8/27
 */
@Slf4j
@RestController
public class DealerUserDetailsControllerImpl implements UserDetailsResource {

    /**
     * user details接口地址
     */
    public static final String USER_DETAILS = "/api/user/details/{username}";

    /**
     * 用户服务
     */
    @Autowired
    private DealerUserService dealerUserService;

    @PostMapping(value = USER_DETAILS, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
        produces = {MediaType.APPLICATION_JSON_VALUE})
    @Override
    public UserInfo loadUserByUsername(@NotNull(message = "用户名不能为空") @PathVariable("username") String username)
        throws UsernameNotFoundException {
        QueryWrapper<DealerUserDO> userQueryWrapper = new QueryWrapper();
        userQueryWrapper.nested(wq -> wq.eq("login_name", username).or().eq("phone", username))
                .eq("disabled", false);
        DealerUserDO userDO = dealerUserService.getOne(userQueryWrapper);
        if (userDO == null) {
            throw new UsernameNotFoundException(String.format("用户名为%s的用户不存在或已被禁用！", username));
        }
        UserInfo userInfo
            = new UserInfo(userDO.getLoginName(), userDO.getLoginPassword(), true, new ArrayList());
        return userInfo;
    }
}
